﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;

/// <summary>
/// WEB端常用方法
/// </summary>
public class UIMethod
{
    public UIMethod()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }

    #region 公共变量
    /// <summary>
    /// 复合型QueryString参数
    /// </summary>
    public static readonly string UI_parameters = "paras";
    /// <summary>
    /// 站点配制信息
    /// </summary>
    public static readonly string UI_SiteConfig = "SiteConfig";
    /// <summary>
    /// 后台样式Cookies名称
    /// </summary>
    public static readonly string UI_StyleName = "StyleName";
    #endregion    

    /// <summary>
    /// 应用程序根目录
    /// </summary>
    /// <returns>“/” 或 “/WebSite/”</returns>
    public static string ApplicationPath()
    {
        string hp = HttpContext.Current.Request.ApplicationPath;
        return (hp.Length > 1) ? hp + "/" : hp;
    }

    /// <summary>
    /// 获取Excel模板的网站路径
    /// </summary>
    /// <returns>相对路径</returns>
    public static string HttpExcelRoot(string file)
    {
        HttpRequest hr = HttpContext.Current.Request;
        return string.Format("{0}://{1}{2}{3}{4}",
            hr.Url.Scheme,//{0}
            hr.Url.Host,//{1}
            ((hr.Url.Port == 80) ? string.Empty : (":" + hr.Url.Port)),//{2}
            ApplicationPath(),//{3}
            file//{4}
            );
    }

    #region 获取参数重载方法
    private static object GetKey(string key)
	{
		System.Web.HttpContext Context = System.Web.HttpContext.Current;
		object queryvalue = Context.Request.QueryString[key];
        if (queryvalue == null) { throw new Exception("没有[" + key + "]参数"); }
        return queryvalue;
	}

	public static void GetQuery(ref string par,string parKey)
	{
		try
		{
			par = Convert.ToString( GetKey(parKey) );
		}
		catch
		{}
	}

	public static void GetQuery(ref string par, string parKey, bool isTrim)
	{
		try
		{
			GetQuery(ref par,parKey);
			
			if( isTrim )
			{
				par = par.Replace(" ","");
                par = par.Replace("'", "");
			}
		}
		catch
		{}
	}

	public static void GetQuery(ref int par,string parKey)
	{
		try
		{
			par = Convert.ToInt32( GetKey(parKey) );
		}
		catch
		{}
	}

	public static void GetQuery(ref long par,string parKey)
	{
		try
		{
			par = Convert.ToInt64( GetKey(parKey) );
		}
		catch
		{}
	}

	public static void GetQuery(ref bool par,string parKey)
	{
		try
		{
			par = Convert.ToBoolean( Convert.ToInt32(GetKey(parKey)) );
		}
		catch
		{}
	}

	public static void GetQuery(ref float par,string parKey)
	{
		try
		{
			par = Convert.ToSingle( GetKey(parKey) );
		}
		catch
		{}
	}

	public static void GetQuery(ref double par,string parKey)
	{
		try
		{
			par = Convert.ToDouble( GetKey(parKey) );
		}
		catch
		{}
	}

    public static void GetQuery(ref DateTime par, string parKey)
    {
        try
        {
            par = Convert.ToDateTime(GetKey(parKey));
        }
        catch
        { }
    }
     
    public static void GetQuery(ref string[] par, string parKey)
    {
        try
        {
            object paras = GetKey(parKey);
            if (paras != null)
            {
                string temp = paras.ToString().Trim();
                temp = temp.Replace("'", string.Empty); //去单引号
                temp = temp.Replace(" ", string.Empty); //去空格

                string[] ps = temp.Split(',');

                List<string> rs = new List<string>();
                foreach (string ts in ps)
                {
                    string tt = ts.Trim();
                    if (tt != string.Empty) { rs.Add(tt); }
                }

                par = rs.ToArray();
            }
        }
        catch
        { }
    }

    /// <summary>
    /// 拆分传递参数
    /// </summary>
    /// <param name="RowGroup">行分解符</param>
    /// <param name="ColumnGroup">列分解符</param>
    /// <param name="Source">源文本</param>
    /// <returns>二维数组</returns>
    public static ArrayList SplitParameters(char RowGroup, char ColumnGroup, string Source)
    {
        ArrayList result = new ArrayList();
        string[] rowlist = Source.Split(RowGroup);  //分解行数组        
        foreach (string temp in rowlist)
        {
            result.Add(temp.Split(ColumnGroup));
        }
        return result;
    }
    /// <summary>
    /// 拆分传递参数(默认 [,|])
    /// </summary>
    /// <param name="Source">源文本</param>
    /// <returns></returns>
    public static ArrayList SplitParameters(string Source)
    {
        return SplitParameters(',', '|', Source);
    }
	#endregion

	#region 客户端脚本
	/// <summary>
	/// 客户端脚本
	/// </summary>
	public static void JS(string scriptkey, string script)
	{
        string output = "<script type='text/javascript'>" + script + "</script>";
        ((System.Web.UI.Page)HttpContext.Current.CurrentHandler).ClientScript.RegisterStartupScript(typeof(string), scriptkey, output);
	}

    /// <summary>
    /// 客户端脚本
    /// </summary>
    public static string JS_str(string script)
    {
        return "<script type='text/javascript'>" + script + "</script>";        
    }

	/// <summary>
	/// 客户端提示框
	/// </summary>		
    public static void Alert(string Msg)
	{
		string output = "alert('" + Msg + "');";
        JS("alert", output);
	}

    /// <summary>
    /// 客户端提示框
    /// </summary>		
    public static string Alert_str(string Msg)
    {
        string output = "alert('" + Msg + "');";
        return JS_str(output);
    }

	/// <summary>
	/// 客户端页面跳转
	/// </summary>		
    public static void GoToURL(string URL, bool IsTop)
	{
        string output = ((IsTop) ? "window.top.location" : "document.location") + " = '" + URL + "';";
		JS("gotourl", output);
	}

    /// <summary>
    /// 客户端页面跳转
    /// </summary>		
    public static string GoToURL_str(string URL, bool IsTop)
    {
        string output = ((IsTop) ? "window.top.location" : "document.location") + " = '" + URL + "';";
        return JS_str(output);
    }

    /// <summary>
    /// 客户端对话框
    /// </summary>
    public static void Confirm(string Msg, string YesAction, string NoAction)
    {
        string output = "if(window.confirm(\"" + Msg + "\")){ " + YesAction + " } else { " + NoAction + " }";
        JS("confirm", output);
    }

    /// <summary>
    /// 客户端对话框
    /// </summary>
    public static string Confirm_str(string Msg, string YesAction, string NoAction)
    {
        string output = "if(window.confirm(\"" + Msg + "\")){ " + YesAction + " } else { " + NoAction + " }";
        return JS_str(output);
    }

    /// <summary>
    /// 浏览器关闭
    /// </summary>		
    public static void Close()
    {
        string output = "window.close();";
        JS("close", output);
    }

    /// <summary>
    /// 浏览器关闭
    /// </summary>		
    public static string Close_str()
    {
        string output = "window.close();";
        return JS_str(output);
    }

    /// <summary>
    /// 重新加页面
    /// </summary>
    public static void ReLoad()
    {
        GoToURL(HttpContext.Current.Request.RawUrl, false);
    }
    /// <summary>
    /// js重新加页面
    /// </summary>
    public static string jsReLoad(bool IsTop)
    {
        string output = ((IsTop) ? "window.top.location" : "document.location") + " = '" + HttpContext.Current.Request.RawUrl + "';";
        return output;
    }
	#endregion	

    #region 高级   
    
    /// <summary>
    /// 返回配制键值
    /// </summary>    
    public static string GetAppSettings(string name)
    {
        return Convert.ToString(ConfigurationManager.AppSettings[name]);
    }    
    /// <summary>
    /// 获取MD5加密
    /// </summary>
    /// <param name="sourceText">源文本</param>
    /// <returns>32位密文</returns>
    public static string GetMD5(string sourceText)
    {
        return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sourceText, "MD5");
    }
    /// <summary>
    /// 获取随机文本(字母或数字)
    /// </summary>
    /// <param name="CharLength">随机数长度</param>
    /// <returns>例： '03A25'</returns>
    public static string RandomWord(int CharLength)
    {
        string[] RandomRange = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
        StringBuilder result = new StringBuilder();
        Random ran = new Random();
        int i = 1;
        int currRan = 0;
        while (i <= CharLength)
        {
            currRan = ran.Next(RandomRange.Length);
            result.Append(RandomRange[currRan]);
            i++;
        }
        return result.ToString();
    }    

    /// <summary>
    /// 获取登录用户编号
    /// </summary>
    /// <returns>没有及错误返回-1</returns>
    public static int GetUserID()
    {
        int result = -1;
        HttpCookie authcook = HttpContext.Current.Request.Cookies["AuthCookie"];

        if (authcook != null && authcook.Value != string.Empty)
        {
            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authcook.Value); //取得身份验证票
            result = Convert.ToInt32(ticket.Name);
        }
        return result;
    }
    /// <summary>
    /// 获取用户的角色
    /// </summary>
    /// <returns>多个角色的数组，反之null</returns>
    public static string[] GetRoles()
    {
        string[] result = null;
        HttpCookie authcook = HttpContext.Current.Request.Cookies["AuthCookie"];

        if (authcook != null)
        {
            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authcook.Value); //取得身份验证票
            result = ticket.UserData.Split(','); //将身份验证票中的role数据转成字符串数组
        }
        return result;
    }
    #endregion


    /// <summary>
    /// 时间问候
    /// </summary>
    /// <returns></returns>
    public static string TimeGreet()
    {
        int mh = DateTime.Now.Hour;
        if (mh <= 12)
        {
            return "早上好";
        }
        else if (mh > 12 && mh <= 14)
        {
            return "中午好";
        }
        else if (mh > 14 && mh <= 18)
        {
            return "下午好";
        }

        return "晚上好";
    }  


    /// <summary>
    /// 获取日期目录
    /// </summary>
    /// <returns>"年/月/日/"</returns>
    public static string GetDateDirectory()
    {
        DateTime t = DateTime.Now;
        StringBuilder sb = new StringBuilder();
        //组合新文件名                
        sb.Append(t.Year).Append("/").Append(t.Month).Append("/").Append(t.Day).Append("/");
        return sb.ToString();
    }
    /// <summary>
    /// 获取时间组合名称
    /// </summary>
    /// <returns>时分秒毫秒</returns>
    public static string GetTimeFileName()
    {
        DateTime t = DateTime.Now;
        StringBuilder sb = new StringBuilder();
        //组合新文件名                
        sb.Append(t.Hour).Append(t.Minute).Append(t.Second).Append(t.Millisecond);
        return sb.ToString();
    }
    /// <summary>
    /// 获取后台样式索引
    /// </summary>
    /// <returns></returns>
    public static string GetStyleValue()
    {
        string result = "1";
        HttpContext hc = HttpContext.Current;
        try
        {
            if (hc.Request.Cookies[UI_StyleName] != null)
            {
                result = hc.Request.Cookies[UI_StyleName].Value;
            }
        }
        catch { }
        return result;
    }

    /// <summary>
    /// 用一个分隔符将一个数组组合成字符串
    /// </summary>
    /// <param name="ArrayObj">数组</param>
    /// <param name="compart">分隔符</param>
    /// <returns>如：a,b,c</returns>
    public static string UniteArray(string[] ArrayObj, string compart)
    {
        if (ArrayObj == null && ArrayObj.Length == 0) { return string.Empty; }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < ArrayObj.Length; i++)
        {
            sb.Append(ArrayObj[i]).Append((i == ArrayObj.Length - 1) ? string.Empty : compart);
        }
        return sb.ToString();
    }

    /// <summary>
    /// 获取异常详细信息中的 错误提示行
    /// </summary>
    /// <param name="errcontent">异常详细信息</param>
    /// <returns>fun.cs:Line 2</returns>
    public static string ExceptionLines(string errcontent)
    {
        StringBuilder sb = new StringBuilder();
        //只抓取 :Line 数字
        string[] lines = errcontent.Split('\n');
        Regex reg = new Regex(@":(line|行号)\s\d+", RegexOptions.IgnoreCase);
        Match m_x = null;
        foreach (string tmp in lines)
        {
            m_x = reg.Match(tmp);
            if (m_x.Success)
            {
                sb.Append(tmp.Replace("\r", string.Empty)).Append("\r\n");
            }
        }
        return sb.ToString();
    }
    
}
